package com.linln.wtp.controller.yearauditOrder;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linln.common.enums.OrderEnum;
import com.linln.common.enums.ServiceTypeEnum;
import com.linln.common.enums.TicketEnum;
import com.linln.common.exception.order.OrderException;
import com.linln.common.utils.ObjectUtil;
import com.linln.common.utils.SessionUtil;
import com.linln.common.vo.JsonResult;
import com.linln.modules.order.domain.OrderTakecaruser;
import com.linln.modules.order.domain.YearauditOrder;
import com.linln.modules.order.service.OrderTakecaruserService;
import com.linln.modules.order.service.YearauditOrderService;
import com.linln.modules.shopsService.service.ShopsService;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.service.UserService;
import com.linln.modules.ticket.domain.Ticket;
import com.linln.modules.ticket.service.TicketService;
import com.linln.modules.vehicle.domain.Vehicle;
import com.linln.wtp.controller.vehicle.VehicleController;
import com.linln.wtp.validator.WxYearauditOrderValid;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("carAnnualReview")
public class YearauditOrderController {
    @Autowired
    VehicleController vehicleController;

    @Autowired
    YearauditOrderService yearauditOrderService;

    @Autowired
    TicketService ticketService;

    @Autowired
    ShopsService shopsService;

    @Autowired
    OrderTakecaruserService orderTakecaruserService;

    @Autowired
    UserService userService;

    /**
     * 获取登录用户车辆信息
     * @return
     */
    @GetMapping("/myVehicle")
    public JsonResult myVehicle() {
        Map map = vehicleController.getVehicles();
        List<Vehicle> vehicleList = (List<Vehicle>) map.get("data");
        List<Map<String,Object>> mapList = new ArrayList<>();
        for(Vehicle vehicle: vehicleList){
            Map m = new HashMap();
            m.put("plate",vehicle.getPlate());
            m.put("ownerName",vehicle.getOwnerName());
            m.put("ownerMobile",vehicle.getOwnerMobile());
            mapList.add(m);
        }
        return JsonResult.ok().put("data",mapList);
    }

    @PostMapping("/buyService")
    public JsonResult buyService(@Validated WxYearauditOrderValid orderValid, YearauditOrder yearauditOrder){
        //服务为上门取车 效验它的一些必传值
        if(orderValid.getService().equals("1")){
            if(Strings.isBlank(yearauditOrder.getPickUpAddress()) ||
               Strings.isBlank(yearauditOrder.getPickUpDate()) ||
               Strings.isBlank(yearauditOrder.getPickUpTime()) ||
               Strings.isBlank(yearauditOrder.getLatitude()) ||
               Strings.isBlank(yearauditOrder.getLongitude())
            ){
                JsonResult.error(400,"上门取车服务类型参数错误");
            }
        }
        Ticket ticket = ticketService.getById(yearauditOrder.getTicketId());

        if(!orderValid.getIsBuy().equals("1") && Strings.isBlank(yearauditOrder.getTicketId())){
            return JsonResult.error(400,"取消成功");
        }

        if((yearauditOrder.getIsTicket() && Strings.isBlank(yearauditOrder.getTicketId())) || ticket==null){
            return JsonResult.error(400,"请使用优惠卷");
        }


        if(ticket.getStatus() == 1){
            return JsonResult.error(400,"优惠卷已被使用");
        }

        try {
            return yearauditOrderService.buyService(yearauditOrder,orderValid.getIsBuy());
        } catch (OrderException e) {
            e.printStackTrace();
            return JsonResult.error(e.getMessage());
        }
    }

    /**
     * 返回当前用户的年审办理优惠卷
     * @return
     */
    @GetMapping("/myticket")
    public JsonResult myticket(){
        Long userId = SessionUtil.getUserId();
        QueryWrapper ticketWrapper = new QueryWrapper();
        ticketWrapper.eq("service_type_id", ServiceTypeEnum.YEARRWVIEW);
        ticketWrapper.eq("user_id",userId);
        ticketWrapper.eq("status", TicketEnum.NOTUSE);
        ticketWrapper.orderByDesc("expir_date");
        List<Ticket> tickets = ticketService.list(ticketWrapper);
        return JsonResult.ok().put("data",new HashMap() {
            {
                if(tickets.size()>0){
                    put("ticketId",tickets.get(0).getTicketId());
                    put("expirDate",tickets.get(0).getExpirDate());
                }else {
                    put("ticketId","");
                }
            }
        });
    }


    /**
     * 分页获取数据
     * @param serviceId
     * @param status
     * @param pageNum
     * @return
     */
    @GetMapping("/orderList")
    public JsonResult orderList(String serviceId, String status, Integer pageNum){
        if(pageNum==null){
            pageNum=0;
        }
        ++pageNum;
        IPage<YearauditOrder> iPage = new Page<>(pageNum,10);
        String orderStatus = "";
        if(serviceId.equals("1")){
            //上门取车
            if(status.equals("0")){
                //全部
            }
            else if(status.equals("1")){
                //待支付
                orderStatus = OrderEnum.WAITPAY.getCode();
            }
            else if(status.equals("2")){
                //待取车
                orderStatus = OrderEnum.WAITINGCAR.getCode();
            }
            else if(status.equals("3")){
                //以取车
                orderStatus = OrderEnum.CARPICKEDUP.getCode();
            }else {
                //已完成
                orderStatus = OrderEnum.COMPLETED.getCode();
            }
        }else {
            //自行前往
            if(status.equals("0")){
                //全部
            }
            if(status.equals("1")){
                //待支付
                orderStatus = OrderEnum.WAITPAY.getCode();
            }
            if(status.equals("2")){
                //已完成
                orderStatus = OrderEnum.COMPLETED.getCode();
            }
        }
        QueryWrapper<YearauditOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",SessionUtil.getUserId());
        queryWrapper.eq("service",serviceId);
        if(Strings.isNotBlank(orderStatus)){
            queryWrapper.eq("status",orderStatus);
        }
        queryWrapper.orderByDesc("create_date");
        iPage = yearauditOrderService.page(iPage,queryWrapper);
        List<Map<String,Object>> mapList = new ArrayList<>();
        for(YearauditOrder order : iPage.getRecords()){
            Map<String,Object> map = new HashMap<>();
            map.put("service",order.getService());
            map.put("orderId",order.getId());
            map.put("status",order.getStatus());
            map.put("create_date",order.getCreateDate());
            map.put("isTicket",order.getIsTicket());
            if(order.getService().equals("1")){
                map.put("pickUpCode",order.getPickUpCode());
            }
            mapList.add(map);
        }
        JsonResult jsonResult = JsonResult.ok();
        jsonResult.put("data",mapList);
        jsonResult.put("total",iPage.getTotal());
        return jsonResult;
    }


    /**
     * 订单详情
     * @param orderId
     * @return
     * @throws IllegalAccessException
     * @throws JSONException
     * @throws InvocationTargetException
     */
    @GetMapping("/orderDetails")
    public JsonResult orderDetails(String orderId) throws IllegalAccessException, JSONException, InvocationTargetException {
        YearauditOrder yearauditOrder = yearauditOrderService.getById(orderId);
        Map<String,Object> map = ObjectUtil.ObjectToMap(yearauditOrder);
        String shopName = shopsService.shopNameById(yearauditOrder.getShopId());
        map.put("phone",yearauditOrder.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
        map.put("shopName",shopName);
        QueryWrapper<OrderTakecaruser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",yearauditOrder.getId());
        OrderTakecaruser orderTakecaruser = orderTakecaruserService.getOne(queryWrapper);
        User user = null;
        if(orderTakecaruser != null){
            user = userService.getById(orderTakecaruser.getUserId());
        }
        //取车人
        map.put("carGet",user==null?"":user.getNickname());
        //取车人电话
        map.put("carGetContact",user==null?"":user.getPhone());
        return JsonResult.ok().put("data",map);
    }

    /**
     * 修改订单状态 取消订单0  完成订单1 删除订单2
     * @param type
     * @param orderId
     * @return
     */
    @PostMapping("/orderUpdateStatus")
    public JsonResult orderUpdateStatus(String type,String orderId){
        UpdateWrapper<YearauditOrder> wrapper = new UpdateWrapper<>();
        boolean flag = false;
        String msg = "";
        if(type.equals("0")){
            //取消订单
            wrapper.eq("id",orderId).set("status",OrderEnum.CANCEL.getCode());
            flag = yearauditOrderService.update(wrapper);
            msg = "取消订单";
        }else if(type.equals("1")){
            //完成订单
            wrapper.eq("id",orderId).set("status",OrderEnum.COMPLETED.getCode());
            flag = yearauditOrderService.update(wrapper);
            msg = "完成订单";
        }else {
            //删除订单
            flag = yearauditOrderService.removeById(orderId);
            msg = "删除订单";
        }
        if(flag){
            return JsonResult.ok(msg+"成功");
        }else {
            return JsonResult.error(msg+"失败");
        }
    }

    /**
     * 支付订单
     * @param orderId
     * @return
     */
    @PostMapping ("/payImmediately")
    public JsonResult payImmediately(String orderId){
        YearauditOrder yearauditOrder = yearauditOrderService.getById(orderId);
        if(yearauditOrder == null){
            return JsonResult.error("支付错误订单不存在");
        }
        //1 为确认支付
        try {
            return yearauditOrderService.buyService(yearauditOrderService.getById(orderId),"1");
        } catch (OrderException e) {
            e.printStackTrace();
            return JsonResult.error(e.getMessage());
        }

    }
}
